package com.ruoyi.system.mail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
public class EmailSender {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisTemplate redisTemplate;


    @Value("${spring.mail.username}")
    private  String setFrom;
//    @Value("${myapp.email.account1.username")
//    private  String accout1;
//    @Value("${myapp.email.account2.username}")
//    private  String accout2;

    /**
     * @param receiverEmail 收件人
     */
    @Async
    public void sendEmail(String receiverEmail) {
        //        四位数验证码
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(setFrom);
        mailMessage.setTo(receiverEmail);
        mailMessage.setSubject("注册验证码");
        mailMessage.setText("您的验证码是：" + randomNumber + ",有效时间为3分钟\nYour verification code is: "+randomNumber+", valid for 3 minutes");
        javaMailSender.send(mailMessage);
        redisTemplate.opsForValue().set(receiverEmail, randomNumber, 3, TimeUnit.MINUTES);
        System.out.println("邮件发送成功！");
    }
}
